<?php
/**
 * @package  quota manage
 */

defined('_JEXEC') or die;

define('COMPANY_ORDER_IMAGE_BASE', JPATH_ROOT.'/images/order');
define('COMPANY_ORDER_IMAGE_BASEURL', JUri::root().'/images/order');

// integrate with job
JLoader::register("Upload", JPATH_SITE.'/components/com_easygallery/class.upload.php/class.upload.php');

require_once(OC_App::getAppPath('company') . "/lib/helper.php");

/**
 * Registration controller class for Users.
 */
class PCompanyModelQuota extends JModelLegacy
{
   /**
    * Get all default quota.
    *
    * @param   string  $qtype  User quota type.
    * @return  array   Default quota info array.
    *
    * @since   3.3
    */
   public function getDefaultQuotas() {
      $db = PFactory::getDbo();
      $query = "SELECT id AS type_id, title, qtype, default_quota FROM #__quota_types";
      $db->setQuery($query);
      $quotaData = $db->loadAssocList('qtype');
       
      if (!empty($quotaData)) {
         foreach ($quotaData as $key=>$quota) {
            $default_quota = json_decode($quota['default_quota'], true);
            $quota = array_merge($quota, $default_quota);
            $quotaData[$key] = $quota;
         }
      }
   
      return $quotaData;
   }
   
   /**
    * Get default quota of given user type.
    *
    * @param   string  $qtype  User quota type.
    * @return  array   Default quota info array.
    *
    * @since   3.3
    */
   public function getDefaultQuota($qtype) {
      if (empty($qtype))
         return null;
      
      $db = PFactory::getDbo();
      $query = "SELECT id AS type_id, title, qtype, default_quota FROM #__quota_types WHERE qtype=" . $db->quote($qtype);
      $db->setQuery($query);
      $quotaData = $db->loadAssoc();
   
      if (!empty($quotaData)) {
         $default_quota = json_decode($quotaData['default_quota'], true);
         $quotaData = array_merge($quotaData, $default_quota);
      }
      
      return $quotaData;
   }
   
   /**
    * Create a order. When success return order id, fail return false.
    *
    * @return  mixed  Bool or integer.
    *
    * @since   3.3
    */
   public function createOrder() {
      if (!PSession::checkToken('post')) {
         $this->setError('页面已失效，请刷新页面');
         return false;
      }
      
      if (!PFactory::isMasterUser()) {
         $this->setError('无权访问');
         return false;
      }
      
      $time = time();
      $db = PFactory::getDbo();
      $config = JFactory::getConfig();
      $user_id = PFactory::getMasterUser()->id;
      $order_type = JRequest::getString('order_type', '');
      $order_date = JFactory::getDate($time)->toSql();
      
      if ($order_type == 'upgrade') {
         $upgrade_type = JRequest::getString('upgrade_type', '');
         $upgradeQuota = $this->getDefaultQuota($upgrade_type);
         if (empty($upgradeQuota)) {
            $this->setError('您购买的账户级别不存在');
            return false;
         }
         
         $order_details = json_encode(
            array(
                  'upgrade_type' => $upgrade_type,
                  'sms_buy_num'  => 0
            )
         );
         $order_content = '账户级别：' . $upgradeQuota['title'];
         
         // create a upgrade order
         $query = "INSERT INTO #__user_quota_orders (user_id, order_num, order_type, order_details, order_content, amount, status, order_date) VALUES " .
                  " (" . $user_id . ", (select CONCAT(auto_increment," . $time . ") from information_schema.TABLES where TABLE_NAME="
                                       . $db->quote(str_replace('#__', $config->get('dbprefix'),  '#__user_quota_orders')) . " and TABLE_SCHEMA='" . $config->get('db') . "'),"
                  . $db->quote($order_type) . ", " . $db->quote($order_details) . ", " . $db->quote($order_content) . ", 0, 1, " . $db->quote($order_date) . ")";
         $db->setQuery($query);
         if (!$db->execute()) {
            $this->setError('升级失败');
            return false;
         }
      } elseif($order_type == 'sms') {
         $sms_buy_num = JRequest::getInt('sms_buy_num', 0);
         if (empty($sms_buy_num)) {
            $this->setError('您购买的短信数目不能为0');
            return false;
         }
         
         $userQuota = PCompanyHelper::getUserQuota();
         
         $order_details = json_encode(
               array(
                     'upgrade_type' => '',
                     'sms_buy_num'  => $sms_buy_num
               )
         );
         
         $order_content = '短信包：' . intval($sms_buy_num) . '条';
         
         $sms_unit_price = $userQuota['sms_unit_price'];
         $amount = $sms_buy_num * $sms_unit_price;
         
         // create a sms order
         $query = "INSERT INTO #__user_quota_orders (user_id, order_num, order_type, order_details, order_content, amount, status, order_date) VALUES " .
                  " (" . $user_id . ", (select CONCAT(auto_increment," . $time . ") from information_schema.TABLES where TABLE_NAME="
                                       . $db->quote(str_replace('#__', $config->get('dbprefix'),  '#__user_quota_orders')) . " and TABLE_SCHEMA='" . $config->get('db') . "'),"
                  . $db->quote($order_type) . ", " . $db->quote($order_details) . ", " . $db->quote($order_content) . ", " . $amount . ", 1, " . $db->quote($order_date) . ")";
         $db->setQuery($query);
         if (!$db->execute()) {
            $this->setError('升级失败');
            return false;
         }
      } else {
         $this->setError('订单类型错误');
         return false;
      }
      
      $query = "UPDATE #__user_quota AS uq SET uq.order_count=(SELECT COUNT(*) FROM #__user_quota_orders WHERE user_id=" . $user_id . ") WHERE uq.user_id=" . $user_id .
               " AND @order_count:=(SELECT COUNT(*) FROM #__user_quota_orders WHERE user_id=" . $user_id . ")";
      $db->setQuery($query);
      if (!$db->execute()) {
         $this->setError('系统错误');
         return false;
      }
      
      // Event Driven Cache/Object Caching - clear any cache related to affected tables
      CacheHelper::triggerRemove($user_id, array('#__user_quota', '#__user_quota_orders'));
      
      $query = "SELECT LAST_INSERT_ID() AS order_id, @order_count AS order_count";
      $db->setQuery($db->useLastConnection($query));
      return $db->loadAssoc();
   }
   
   /**
    * Get a order by id.
    *
    * @param   integer  $order_id  Order id.
    * @return  array    Order info array.
    *
    * @since   3.3
    */
   public function getOrder($order_id = 0) {
      $db = PFactory::getDbo();
      $query = "SELECT order_num, order_type, order_content, amount FROM #__user_quota_orders WHERE id=" . intval($order_id) . " AND user_id=" . PFactory::getMasterUser()->id;
      $db->setQuery($query);
      return $db->loadAssoc();
   }
   
   /**
    * Save sms settings.
    *
    * @return  boolean  Success return true.
    *
    * @since   3.3
    */
   public function saveSmsSettings() {
      if (!PSession::checkToken('post')) {
         $this->setError('页面已失效，请刷新页面');
         return false;
      }
   
      if (!PFactory::isMasterUser()) {
         $this->setError('无权访问');
         return false;
      }
      
      $post_settings = JRequest::getVar('email_sms_settings', array(), 'POST', 'array');
      $post_settings_jobstatus=JRequest::getVar('email_sms_settings_jobstatus', array(), 'POST', 'array');
      // settings keys config
      $settings_keys = array(
            'email_jobstatus_weekly',
            'email_jobsaved',
            'email_remind_event_owner',
            'sms_onlineinterview_0h',
            'sms_onlineinterview_48h',
            'sms_offlineinterview_0d',
            'sms_offlineinterview_1d',
            'sms_offer_0d',
            'sms_offer_1d'
      );
      
      $settings = array();
      foreach ($settings_keys as $skey) {
         if($skey=='email_jobstatus_weekly'){
            $settings[$skey] = (count($post_settings_jobstatus)>0) ? implode(',', $post_settings_jobstatus):'';
         }else{
            $settings[$skey] = (isset($post_settings[$skey]) && $post_settings[$skey]) ? 1 : 0;
         }     
      }
      $db = PFactory::getDbo();
      $user_id = PFactory::getMasterUser()->id;
      $query = "INSERT INTO #__email_sms_settings (user_id, settings, modified) VALUES (" . $user_id . ", " . $db->quote(json_encode($settings)) . ", UTC_TIMESTAMP()) " .
               "ON DUPLICATE KEY UPDATE settings=VALUES(settings), modified=VALUES(modified)";
      $db->setQuery($query);
      
      if (!$db->execute()) {
         $this->setError('保存失败');
         return false;
      }
      
      // Event Driven Cache/Object Caching - clear any cache related to affected tables
      CacheHelper::triggerRemove($user_id, array('#__email_sms_settings'));
      
      return true;
   }
   
   /**
    * Get company order history list.
    *
    * @return  object  Order object list
    *
    * @since   3.3
    */
   public function getOrderList() {
      $db = PFactory::getDbo();
      $user_id = PFactory::getMasterUser()->id;
      $query = "SELECT SQL_CALC_FOUND_ROWS id, order_num, order_type, order_content, amount, receipt_pic, status, order_date, expired_date FROM #__user_quota_orders WHERE user_id=" . $user_id . " ORDER BY order_date DESC";
   
      $limitstart = JRequest::getVar('limitstart', 0, '', 'int');
   
      // Get the pagination request variables
      $app = PFactory::getApplication();
      $limit = $app->getUserStateFromRequest('jobpos.limit', 'limit', 10, 'int');
      $limit = $limit > 100 ? 100 : $limit;
   
      // In case limit has been changed, adjust limitstart accordingly
      $limitstart = ( $limit != 0 ? (floor( $limitstart / $limit ) * $limit) : 0);
   
      /* try to load from cache */
      $cache = CacheHelper::getCache('app_company');
      // get cached data now
      list($result, $total) = $cache->call(array($this, '_getOrderList'), $query, intval($limitstart), intval($limit));
   
      // Event Driven Cache/Object Caching
      // there are the tables which we need to invoke cache cleaning triggers when tables are changed by user - Event Driven Cache/Object Caching
      CacheHelper::setTriggers($user_id, $cache, array('#__user_quota_orders'));
   
      // generate html output now
      $pagination = new PPagination( $total, $limitstart, $limit);
   
      return array($result, $pagination);
   }
    
   public function _getOrderList($query, $limitstart=0, $limit=0) {
      $db = PFactory::getDbo();
      $db->setQuery($query, $limitstart, $limit);
      $result = $db->loadObjectList();
       
      $db->setQuery($db->useLastConnection('SELECT FOUND_ROWS();'));
      $total = $db->loadResult();
      return array($result, $total);
   }
   
   /**
    * Get company sms send history list.
    *
    * @return  object  Sms object list.
    *
    * @since   3.3
    */
   public function getSmsHistory() {
      $db = PFactory::getDbo();
      $user_id = PFactory::getMasterUser()->id;
      $query = "SELECT SQL_CALC_FOUND_ROWS to_name, title, created FROM #__sms_history WHERE user_id=" . $user_id . " ORDER BY created DESC";
      
      $limitstart = JRequest::getVar('limitstart', 0, '', 'int');
      
      // Get the pagination request variables
      $app = PFactory::getApplication();
      $limit = $app->getUserStateFromRequest('jobpos.limit', 'limit', 10, 'int');
      $limit = $limit > 100 ? 100 : $limit;
      
      // In case limit has been changed, adjust limitstart accordingly
      $limitstart = ( $limit != 0 ? (floor( $limitstart / $limit ) * $limit) : 0);
      
      /* try to load from cache */
      $cache = CacheHelper::getCache('app_company');
      // get cached data now
      list($result, $total) = $cache->call(array($this, '_getSmsHistory'), $query, intval($limitstart), intval($limit));
      
      // Event Driven Cache/Object Caching
      // there are the tables which we need to invoke cache cleaning triggers when tables are changed by user - Event Driven Cache/Object Caching
      CacheHelper::setTriggers($user_id, $cache, array('#__sms_history'));
      
      // generate html output now
      $pagination = new PPagination( $total, $limitstart, $limit);
      
      return array($result, $pagination);
   }
   
   public function _getSmsHistory($query, $limitstart=0, $limit=0) {
      $db = PFactory::getDbo();
      $db->setQuery($query, $limitstart, $limit);
      $result = $db->loadObjectList();
   
      $db->setQuery($db->useLastConnection('SELECT FOUND_ROWS();'));
      $total = $db->loadResult();
      return array($result, $total);
   }
   
   /**
    * Set order status.
    *
    * @param   integer  $order_id  Order id.
    * @param   integer  $status    Status id.
    * @return  boolean  Success return true
    *
    * @since   3.3
    */
   public function setOrderStatus($order_id = 0, $status) {
      if (!PSession::checkToken('post')) {
         $this->setError('页面已失效，请刷新页面');
         return false;
      }
       
      if (!PFactory::isMasterUser()) {
         $this->setError('无权访问');
         return false;
      }
   
      $db = PFactory::getDbo();
      $user_id = PFactory::getMasterUser()->id;
      $query = "UPDATE #__user_quota_orders SET status=" . intval($status) . " WHERE status!=100 AND user_id=" . $user_id . " AND id=" . intval($order_id);
      $db->setQuery($query);
   
      if (!$db->execute()) {
         $this->setError('订单状态保存失败');
         return false;
      }
      
      CacheHelper::triggerRemove($user_id, array('#__user_quota_orders'));
   
      return true;
   }
   
   /**
    * Get order receipt picture by id.
    *
    * @param   integer  $order_id  Order id.
    * @return  object   Order info object.
    *
    * @since   3.3
    */
   public function getReceiptPic($order_id = 0) {
      $db = PFactory::getDbo();
      $query = "SELECT order_num, receipt_pic FROM #__user_quota_orders WHERE id=" . intval($order_id) . " AND user_id=" . PFactory::getMasterUser()->id;
      $db->setQuery($query);
      return $db->loadAssoc();
   }
   
   /**
    * Upload order receipt picture.
    *
    * @param   integer  $order_id  Order id.
    * @return  object   Order info object.
    *
    * @since   3.3
    */
   public function uploadReceipt($order_id = 0) {
      $order_id = JRequest::getInt('order_id', 0);
      if (empty($order_id)) {
         $this->setError('网络异常，请重试！');
         return false;
      }
      
      if (!PSession::checkToken('post')) {
         $this->setError('页面已失效，请刷新页面！');
         return false;
      }

      $order = $this->getOrder($order_id);
      if (!PFactory::isMasterUser() || empty($order)) {
         $this->setError('无权访问');
         return false;
      }
      
      $files = JRequest::get('files');
      $user_id = PFactory::getMasterUser()->id;
      
      if(!empty($files['Filedata']['name'])) {
         $image_data = $files['Filedata'];
         $fileext = JFile::getExt($image_data['name']);
         $image_data['name'] = JApplication::stringURLSafe(JFile::stripExt($image_data['name'])) . "." . $fileext;
         $file_id = $order['order_num'];
      
         $target_path = JPath::clean(COMPANY_ORDER_IMAGE_BASE.'/'.$user_id.'/');
      
         if(!JFolder::exists($target_path))
            JFolder::create($target_path);
      
         $handle = new Upload($image_data, 'zh_CN');
         if ($handle->uploaded) {
            $handle->allowed = array("image/*");
            $handle->file_src_name_body = $file_id; // hard name
            $handle->file_overwrite = true;
            $handle->file_auto_rename = false;
            $handle->image_resize = false;
            $handle->process($target_path);
            if (!$handle->processed) {
               $this->setError($handle->error);
               return false;
            }
            // set stats
            $filename = $handle->file_dst_name;
      
            $handle-> clean();
         }
         else {
            $this->setError($handle->error);
            return false;
         }
      
      } else {
         $this->setError('系统错误');
         return false;
      }
      
      $db = PFactory::getDbo();
      $query = "UPDATE #__user_quota_orders SET receipt_pic=" . $db->quote($filename) . " WHERE user_id=" . $user_id . " AND id=" . intval($order_id);
      $db->setQuery($query);
      if (!$db->execute()) {
         $this->setError('上传失败');
         return false;
      }
      
      CacheHelper::triggerRemove($user_id, array('#__user_quota_orders'));
      
      return true;
   }
   
   public function setCompanyCollectionQuota(){
      if(!OC_User::isLoggedIn()) {
         $this->setError('请先登录');
         return false;
      }
      if(PFactory::isJobseekerUser()) {
         $this->setError('您无权访问该资源');
         return false;
      }
      $jobsaved=JRequest::getInt('collect',0);
      $user=PFactory::getMasterUser();     
      if(PCompanyHelper::isJobManager() && !PFactory::isMasterUser()){
         OC_Preferences::setValue(OC_User::getUser(),'company','show_jobsaved',$jobsaved);
      }else{
         OC_Preferences::setValue($user->id,'company','show_jobsaved',$jobsaved);
      } 
      CacheHelper::triggerRemove(OC_User::getUser(), array('#__jobs_job','*PREFIX*preferences'));
      return true;
   }
}


